package zct.proj.customView;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import zct.proj.pojo.EquipmentInfo;
import zct.proj.pojo.StationInfo;
import zct.proj.pojo.StationSummary;
import zct.proj.util.Const;
import zct.proj.util.DrawUtil;
import zct.proj.util.IniParser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;

public class TouchView extends ImageView
{
    private float beforeLenght;
    private float afterLenght;
    private boolean multiFinger = false;
   
    private int tw;
    private int th;
    
    private float x0;
    private float y0;
    
    private float w0;
    private float h0;
    private float l0;
    private float t0;
    
    private float rx0;
    private float ry0;
    
    private float scale;
    private Context ctx;
    DrawUtil drawUtil;
    ArrayList<EquipmentInfo> sbList = new ArrayList<EquipmentInfo>();
    TouchView me;
    int lastLeft;
    int lastTop;
	
    private TranslateAnimation trans;
    
    public TouchView(Context context)
	{
		super(context);
		me = this;
		this.setPadding(0, 0, 0, 0);
		Display disp = ((Activity)context).getWindowManager().getDefaultDisplay();
		tw = disp.getWidth();
		th = disp.getHeight();
		ctx = context;
		
		
		
		StationInfo sInfo = IniParser.getStationInfo(context);
		StationSummary ss = sInfo.getStationSummary();
    	drawUtil = new DrawUtil(context, ss, 1);
    	// 获得所有控件信息
    	sbList = sInfo.getCtlList();
    	// 绘制各个控件
//    	drawUtil.drawNet();
    	drawUtil.drawControls(sbList);
    	
    	setImageBitmap(drawUtil.getCacheBitmap());
    	setLayoutParams(new AbsoluteLayout.LayoutParams(1140, 670, 0, 0));
	}
	
    /**
	 * 计算两点间的距离
	 */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }
    
    /**
     * 处理触碰..
     */
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{	
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
//    		mode = DRAG;
//	    	x1 = (int) event.getRawX();
//	    	y1 = (int) event.getRawY();
    		if (event.getPointerCount() >= 2) {
    			getBasePostion(event, false);
//        		Log.v("ActionDownMulti", x0 + "," + y0);
    		} else {
    			getBasePostion(event, true);
//            	Log.v("ActionDownSingle", x0 + "," + y0);
    		}
    		multiFinger = true;
//        	if(event.getPointerCount()==2)
//        		beforeLenght = spacing(event);
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
//            if (spacing(event) > 10f) {
//                    mode = ZOOM;
//            		beforeLenght = spacing(event);
//            }
        	if (event.getActionIndex() == 1 && multiFinger) {
        		getBasePostion(event, false);
        	}
//    		Log.v("PointerDown", x0 + "," + y0);
            break;
        case MotionEvent.ACTION_UP:
    		/*判断是否超出范围     并处理*/
    		int left = this.getLeft();
    		int right = this.getRight();
    		int top = this.getTop();
    		int bottom = this.getBottom();
    		int w = right - left;
    		int h = bottom - top;
    		int offX = 0;
    		int offY = 0;
    		
    		if (w < tw && h < th) {
    			Log.v("zoom", "<<<<<<<<");
    			float zoomW = tw / w;
    			float zoomH = th / h;
    			if (zoomW < zoomH) {
    				left = 0;
    				right = tw;
    				w = tw;
    				h = (int) (zoomW * h);
//    				top = (th - zoomW * h) / 2;
    			} else {
    				top = 0;
    				bottom = th;
    				h = th;
    				w = (int) (zoomH * w);
    			}
    		}
//    		Log.v("size", this.getLeft() + "," + this.getRight() + "," + (this.getRight() - this.getLeft()) + "," + this.getWidth());
//    		Log.v("vvvv", w + "," + tw + "," + h + "," + th);
    		// 长或宽大于屏幕尺寸时，移动到边缘
    		if (w >= tw) {
    			if (left > 0) {
    				offX = -left;
    			} else if (right < tw) {
    				offX = tw - right;
    			}
    		} else {
    			offX = (tw - w) / 2 - left;
    		}
    		
    		if (h >= th) {
    			if (top > 0) {
    				offY = -top;
    			} else if (bottom < th) {
    				offY = th - bottom;
    			}
    		} else {
    			offY = (th - h) / 2 - top;
    		}
    		
//    		drawUtil.zoom(scale);
//    		drawUtil.drawControls();
    		
//    		this.layout(left + offX, top + offY, right + offX, bottom + offY);
//    		trans = new TranslateAnimation(-offX, 0, -offY, 0);
//    		trans.setDuration(500);
//    		this.startAnimation(trans);
    		moveView(offX, offY, true);
//        	mode = NONE;
    		break;
        case MotionEvent.ACTION_POINTER_UP:
//            mode = NONE;
        	if (!multiFinger) {
        		break;
        	}
        	if (event.getActionIndex() == 1) {
        		multiFinger = false;
        		getBasePostion(event, true);
        	}
        	
//        	Log.v("p up", event.getActionIndex() + "");
        	
            break;
        case MotionEvent.ACTION_MOVE:

//        	int x1 = 0;
//        	int y1 = 0;
        	if (multiFinger && event.getPointerCount() >= 2) {
            	scale = 1f;
            	if (beforeLenght > 0) {
            		// 执行缩放
            		afterLenght = spacing(event);
            		scale = afterLenght / beforeLenght;
            	}
            	
            	int newW = (int) (w0 * scale);
            	int newH = (int) (h0 * scale);
//            	float x1 = (int) ((event.getX(1) + event.getX()) / 2);
//            	float y1 = (int) ((event.getY(1) + event.getY()) / 2);
            	
//            	int newL = (int) (l0 - newW * (x0 / w0) + x0);
//            	int newT = (int) (t0 - newH * (y0 / h0) + y0);
            	
            	int newL = (int) (l0 - newW * (x0 / w0) + x0 + event.getRawX() - rx0);
            	int newT = (int) (t0 - newH * (y0 / h0) + y0 + event.getRawY() - ry0);
            	this.layout(newL, newT, newW + newL, newH + newT);
        	} else {
            	int xDis = (int) (event.getX() - x0);
            	int yDis = (int) (event.getY() - y0);
            	moveView(xDis, yDis, false);
//            	this.layout(this.getLeft() + xDis, this.getTop() + yDis, this.getRight() + xDis, this.getBottom() + yDis);
        	}
        	

        	
        	
//        	if (event.getPointerCount() >= 2) {
//        		
//        	}
//        	int xDis = (int) (event.getX() - x0);
//        	int yDis = (int) (event.getY() - y0);
//        	Log.v("newPos", event.getX() + "," + event.getY());
//        	Log.v("distance", xDis + "," + yDis);
//        	this.layout(this.getLeft() + xDis, this.getTop() + yDis, this.getRight() + xDis, this.getBottom() + yDis);
//        	this.layout(this.getLeft(), this.getTop(), this.getRight(), this.getBottom());

            break;
        }
        return true;	
	}
	
	private void getBasePostion(MotionEvent event, boolean singlePT) {
		
		if (singlePT) {
			// 单点
			x0 = event.getX();
			y0 = event.getY();
			beforeLenght = 0;
		} else {
			// 多点
			x0 = (event.getX() + event.getX(1)) / 2;
			y0 = (event.getY() + event.getY(1)) / 2;
			beforeLenght = spacing(event);
		}
		w0 = this.getWidth();
		h0 = this.getHeight();
		l0 = this.getLeft();
		t0 = this.getTop();
		rx0 = event.getRawX();
		ry0 = event.getRawY();
	}
	
	private final Timer timer = new Timer();
	private TimerTask task;
	Handler handler;
	private int lampColor;

	public void drawSome() {
	
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				//要做的事情
				
				if (msg.what == 1) {
					
					int cnt = 0;
					if (lampColor == Color.RED) {
						lampColor = Color.GREEN;
//						Log.v("tv", "green");
					} else {
						lampColor = Color.RED;
//						Log.v("tv", "red" + sbList.size());
					}
					for (int i = 0, len = sbList.size(); i < len; i++) {
						EquipmentInfo ei = sbList.get(i);
						if (ei.getName().equals(Const.EQUI_DHAN) && ei.getType() < 3) {
//							Log.v("tv", "got");
							Paint p = new Paint();
							p.setColor(Color.BLUE);
							drawUtil.drawSbDHANLamp(ei, lampColor);
							cnt ++;
							if (cnt >= 10) {
//								Log.v("tv", me.getLeft() + " beform");
								//me.setImageBitmap(drawUtil.getCacheBitmap());
//								Log.v("tv", me.getLeft() + " beform");
//								me.layout(-100, -100, me.getTop() - 100, me.getBottom() - 100);
								Bitmap cache = drawUtil.getCacheBitmap();
								Matrix m = new Matrix();
								m.postScale(1, 1);
								Bitmap bmp = Bitmap.createBitmap(cache, 100, 100, cache.getWidth() + 100, cache.getHeight() + 100, m, true);
								me.setImageBitmap(bmp);
//								Log.v("tv", me.getLeft() + " after");
//								moveView(lastLeft, lastTop, false);
//								Log.v("tv", me.getLeft() + " beform");
//								me.invalidate();
//								Log.v("tv", me.getLeft() + " after");
								break;
							}
						}
					}
				}
				//super.handleMessage(msg);
			}
		};
		
		task = new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}
		};

		timer.scheduleAtFixedRate(task, 2000, 2000);
	}
	
	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Log.v("tv", "onDraw");
//		if (this.getLeft() != lastLeft && this.getTop() != lastTop) {
//			moveView(lastLeft, lastTop, false);
//			Log.v("onDrawLeft", this.getLeft() + "");
//		}
		
	}
	
	private void moveView(int offX, int offY, boolean animate) {
		
		lastLeft = me.getLeft() + offX;
		lastTop = me.getTop() + offY;
		me.layout(lastLeft, lastTop, getRight() + offX, getBottom() + offY);
		
		if (animate) {
			trans = new TranslateAnimation(-offX, 0, -offY, 0);
			trans.setDuration(500);
			me.startAnimation(trans);
		}
	}
}
